<?php
class Custom_Keysearch_Wonder
{

    public function getKeyword($argv) 
    {
        $parent_pages = array('wonder' => array(), 'related_searches' => array());

        $wonder = $this->getWonderWheelResult($argv);
        if ($wonder) {
            foreach ($wonder as $key => $term) {
                $parent_pages['wonder'][$key]['term'] = $term;
                $childPage = $this->getWonderWheelResult($term);
                if ($childPage) {
                    $parent_pages['wonder'][$key]['children'] = $childPage;
                }
            }
        }

        echo "Getting Related Searches Results...\n";
        $wonder = $this->getRelatedSearches($argv);
        if ($wonder) {
            foreach ($wonder as $key => $term) {
                $parent_pages['related_searches'][$key]['term'] = $term;
                $childPage = $this->getRelatedSearches($term);
                if ($childPage) {
                    $parent_pages['related_searches'][$key]['children'] = $childPage;
                }
            }
        }


        //print_r($parent_pages);
        return $parent_pages;
    }

    public  function hexDecode($string)
    {
        return preg_replace("#(\\\x[0-9A-Fa-f]{2})#e", "chr(hexdec('\\1'))", $string);
    }

    public function getWonderWheelResult($string)
   {
        $curl = new Custom_Keysearch_Curl();
        $curl->Initialize();
        $result = $curl->GetUrl('http://www.google.com/search?q=' . urlencode($string) . '&hl=en&sa=G&tbo=1&tbs=ww:1&prmd=ivnscm&bav=on.2,or.r_gc.r_pw.&fp=afe4d9086b9a4cf8&biw=1885&bih=496&tch=1&ech=1&psi=SCHCTfrZHsnirAfk8_HnAw13045681426853');
        $curl->FreeMemory(true);
        $result = $this->hexDecode($result);
        if (preg_match_all('/parent\.google\.ww\.r\((.*?)\)/is', $result, $matches)) {
            $wonder = json_decode(stripslashes($matches[1][0]), true);
            return $wonder['r'];
        }
        return false;
    }

    public function getRelatedSearches($string) 
    {
        $domhtml = new Custom_Html_Dom();
        //$domnode = new Custom_Html_Dom_Node();
        
        $curl = new Custom_Keysearch_Curl();
        $curl->Initialize();
        $result = $curl->GetUrl('http://www.google.com/search?q=' . urlencode($string) . '&hl=en&safe=off&tbo=1&biw=1680&bih=848&output=search&source=lnt&tbs=clue:1&sa=X&ei=UjTCTZHLI8iGrAeQpOTqAw&ved=0CA4QpwUoAw');
        $curl->FreeMemory(true);
        $result = $this->hexDecode($result);
        
        $return = array();
        foreach ($domhtml->str_get_html($result)->find('div[id=tbt5] > div > ol > li > a') as $key => $div) {
            $return[] = htmlspecialchars_decode($div->plaintext, ENT_QUOTES);
        }
        unset($html);
        if (count($return)) {
            return $return;
        } else {
            return false;
        }
    }
   
}

?>
